$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'employee/list',
        datatype: "json",
        colModel: [
			{ label: 'dataId',hidden:true, name: 'dataId', index: 'dataId'},
			{ label: 'userId',hidden:true, name: 'userId', index: 'userId', width: 50, key: true},
			{ label: '所属经营主体', name: 'subjectName', width: 120 },
			{ label: '姓名', name: 'name', width: 60 },
			{ label: '所属部门', name: 'deptName', width: 80 },
			{ label: '员工角色', name: 'employeeRole', width: 80 },
			{ label: '性别', name: 'sex', width: 35, formatter: function(value, options, row){
				return value === 0 ?
					'<span>男</span>' : 
					'<span>女</span>';
			}},
			{ label: '员工类型', name: 'type', width: 80, formatter: function(value, options, row){
				return value === 0 ? 
					'<span>合同工</span>' : 
					'<span>临时工</span>';
			}},				
			{ label: '手机号', name: 'mobile', width: 80 }, 						
			{ label: '学历', name: 'educationName',width: 75 },
			{ label: '是否贫困户', name: 'ispoor', width:70, formatter: function(value, options, row){
				return value === 0 ? 
					'<span>否</span>' : 
					'<span>是</span>';
			}},
			{ label: '状态', name: 'status', width:40, formatter: function(value, options, row){
				return value === 0 ? 
					'<span class="label label-danger">离职</span>' :
					'<span class="label label-success">正常</span>';
			}},		
			{ label: '创建时间', name: 'createTime', index: 'create_time', width: 80 }			
        ],
		viewrecords: true,
        height: (pageInfo().height-130),
        rowNum: 15,
		rowList : [15,50,99],
        loadtext : '<img src="../../statics/plugins/layer/skin/default/loading-1.gif" style="margin-right:10px;"/>正在加载,请稍候……',
        rownumbers: false,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        beforeRequest : function(){},
        loadComplete : function(data){
            if(data.code == 0){
                return data;
            }else if(data.code == 205){
                invalidAccess();
            }else{
                layer.alert(data.msg);
            }
        },
        loadError : function(xhr,status,error){},
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });

    thisPage = {
        initDom : function(){
            this.getTypeEducation();
            this.getTypeEmployeeRoles();
            this.getTypeDept();
        },
        /**基地学历*/
        getTypeEducation : function(){
            ajaxQuery(baseURL + 'employee/getTypeEducation',{},function(data){
                setDataSelect('选择学历','#education_id',data.data,'value','text');
            });
        },
        getTypeEmployeeRoles : function(){
            ajaxQuery(baseURL + 'employee/getTypeRoles',{},function(data){
                setDataSelect('选择员工角色','#isassociator',data.data,'value','name');
            });
        },
        getTypeDept : function(){
            ajaxQuery(baseURL + 'employee/getTypeDept',{},function(data){
                setDataSelect('选择所属部门','#deptId',data.data,'value','name');
            });
        }
    }
    thisPage.initDom();
});

var setting = {
    data : {
        simpleData : {
            enable : true,
            idKey : "deptId",
            pIdKey : "parentId",
            rootPId : 0
        },
        key : {
            url:"nourl"
        }
    }
};
var ztree;

var vm = new Vue({
	el:'#witapp',
	data:{
		showList: true,
		title: null,
		employee: {},
		q:{
            key: null
        }
	},
	methods: {
		query: function () {
			vm.reload();
		},
        addEmployee: function(){
            $('#userId').val('');
            this.openDialog();
		},
        getDept: function(){
            $.get(baseURL + "employee/deptList", function(r){
                ztree = $.fn.zTree.init($("#deptTree"), setting, r.deptList);
                var node = ztree.getNodeByParam("deptId", vm.employee.parentId);
                if(node){
                    ztree.selectNode(node);
                    vm.employee.parentName = node.name;
                }
            });
        },
        editEmployee : function(){
            var dataRow = getDataRow();
            if(dataRow){
                var dataId = dataRow['dataId'];
                var userId = dataRow['userId'];
                $('#userId').val(userId);
                var _this = this;
                ajaxQuery(baseURL + "employee/get/"+dataId,{},function(data){
                    if(data.code == 0){
                        _this.openDialog(dataId,data.data);
                    }else{
                        alert(data.msg);
                    }
                });
            }
        },
        resetPassword : function(){
            var dataRow = getDataRow();
            if(dataRow){
                var userId = dataRow['userId'];
                var mobile = dataRow['mobile'];
                top.layer.prompt({title:'为['+mobile+']重置新的密码'},function(val,indexTemp){
                    var expr = /([a-zA-Z0-9!@#$%^&*()_?<>{}]){6,16}/;
                    if(!expr.test(val)){
                        alert("密码长度在6-16位!");
                        return;
                    }
                    top.layer.close(indexTemp);
                    ajaxExecute("/employee/resetPassword?value="+val+"&userId="+userId,{},function(data){
                        if(0 == data.code){
                            dialogResult(data.msg);
                        }else{
                            alert(data.msg);
                        }
                    });
                });
            }
        },
        openDialog : function(kid,map){
            var loginUser = sessionStorage.getItem("loginUser") || '';
            if(loginUser == 'admin'){
                alert('无权限操作');
                return;
            }
            var url = 'employee/save';
            var title = '添加员工信息';
            if(kid != null && kid.length >0){
                url = 'employee/update?data_id='+kid;
                title = '编辑员工信息';
            }
            $('#framImages').val('');//清空证件照
            var loginUser = sessionStorage.getItem("loginUser");
            if(loginUser == 'admin'){
                $('#div_employee_username').css({"display":""});
            }else{
                $('#div_employee_username').css({"display":"none"});
            }
            addOrEdit(title,'#div_employee_dialog',['600px','520px'],function(indexLayero,layero){
                var user_name = $('#user_name').val();
                var name = $('#name').val();
                var deptId = $('#deptId').val();
                var deptName = $('#deptId').find("option:selected").text();
                var card_id = $('#card_id').val();
                var sex = $("input[name='sex']:checked").val();
                var ispoor = $("input[name='ispoor']:checked").val();
                var type = $("input[name='type']:checked").val();
                var mobile = $('#mobile').val();
                var education_id = $('#education_id').val();
                var education_name = $('#education_id').find("option:selected").text();
                var wagestype = $("input[name='wagestype']:checked").val();
                var isassociator = $('#isassociator').val();
                var isassociator_name = $('#isassociator').find("option:selected").text();
                var status = $("input[name='status']:checked").val();
                var synopsis = $('#synopsis').val();
                if(loginUser == 'admin'){
                    if(user_name == null || user_name.length <= 0){
                        alert("请填写经营主体登录账号");
                        return;
                    }
                }
                if(name == null || name.length <= 0){
                    alert("请填写员工姓名");
                    return;
                }
                if(deptId == null || deptId.length <= 0){
                    alert("请选择所属部门");
                    return;
                }
                if(card_id == null || card_id.length <= 0){
                    alert("请填写身份证号码");
                    return;
                }
                var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                if(!reg.test(card_id)){
                    alert("身份证号码有误");
                    return;
                }
                if(sex == null || sex.length <= 0){
                    alert("请选择员工性别");
                    return;
                }
                if(ispoor == null || ispoor.length <= 0){
                    alert("请选择是否贫困户");
                    return;
                }
                if(type == null || type.length <= 0){
                    alert("请选择员工类型");
                    return;
                }
                if(mobile == null || mobile.length <= 0){
                    alert("请填写员工手机号码");
                    return;
                }
                var expr = new RegExp("^1[34578][0-9]{9}$",'i');
                if(!expr.test(mobile)){
                    alert("手机号码有误!");
                    return;
                }
                if(education_id == null || education_id.length <= 0){
                    alert("请选择学历");
                    return;
                }
                if(wagestype == null || wagestype.length <= 0){
                    alert("请选择计工类型");
                    return;
                }
                if(isassociator == null || isassociator.length <= 0){
                    alert("请选择员工角色");
                    return;
                }
                var params = {
                    user_name : user_name,
                    name : name,
                    deptId : deptId,
                    deptName : deptName,
                    card_id : card_id,
                    sex : sex,
                    ispoor : ispoor,
                    userId : $('#userId').val(),
                    type : type,
                    mobile : mobile,
                    education_id : education_id,
                    education_name : education_name,
                    wagestype : wagestype,
                    isassociator : isassociator,
                    isassociator_name : isassociator_name,
                    status : status,
                    synopsis : synopsis
                }
                var formData = new FormData();
                for(var key in params){
                    formData.append(key,params[key]);
                }
                var files = document.getElementById("framImages").files;
                for(var index in files){
                    formData.append("image"+index,files[index]);
                }
                formSubmit(url,formData,function(data){
                    if(0 == data.code){
                        layer.close(indexLayero);
                        vm.reload();
                    }else{
                        alert(data.msg);
                    }
                });
            });
            if(kid != null && kid.length > 0){
                $("#user_name").attr("disabled","disabled");
                $("#showImages").css("display","");
                this.renderDom(map);
            }else{
                $("#showImages").css("display","none");
                $('#showImages').empty();
                $("#user_name").removeAttr('disabled');
            }
        },
        renderDom : function(map){
            for(var k in map){
                var v = map[k]+'';
                if(k == 'status'){
                    $("input[name='status'][value="+v+"]").attr("checked",true);
                }else if(k == 'sex'){
                    $("input[name='sex'][value="+v+"]").attr("checked",true);
                }else if(k == 'ispoor'){
                    $("input[name='ispoor'][value="+v+"]").attr("checked",true);
                }else if(k == 'type'){
                    $("input[name='type'][value="+v+"]").attr("checked",true);
                }else if(k == 'wagestype'){
                    $("input[name='wagestype'][value="+v+"]").attr("checked",true);
                }else if(k == 'pic'){
                    var html = "<div class=\"col-sm-12\">";
                    var graphic = v.split(',');
                    for (var i = 0; i<graphic.length; i++){
                        html+='<div class="col-sm-2"></div>';
                        html+='<a class="col-sm-10" style="color:#459df5;" title="点击查看证件照" target="_blank" href="../..'+graphic[i]+'">证件照'+(i+1)+'</a>';
                    }
                    html+="</div>";
                    $('#showImages').empty().append(html);
                }else{
                    $('#'+k).val(v);
                }
            }
        },
        viewEmployee: function (event) {
            var dataRow = getDataRow();
            if(dataRow){
                var dataId = dataRow['dataId'];
                vm.showList = false;
                vm.title = "查看";
                vm.getInfo(dataId)
            }
		},
		del: function (event) {
            var dataIds = $("#jqGrid").getGridParam("selarrrow");
            if(dataIds.length <= 0){
                alert("请选择要删除员工");
                return;
            }
            confirm('确定要删除['+dataIds.length+']条数据吗？',function(){
                ajaxExecute(baseURL + "employee/delete",JSON.stringify(dataIds),function(data){
                    if(data.code == 0){
                        $("#jqGrid").trigger("reloadGrid");
                    }else{
                        alert(data.msg);
                    }
                });
            });
		},
		getInfo: function(dataId){
		    ajaxQuery("employee/info/"+dataId,{},function(data){
		        if(0 == data.code){
                    vm.employee = data.employee;
                }else{
                    alert(data.msg);
                }
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
				postData:{'key': vm.q.key},
                page:page
            }).trigger("reloadGrid");
		}
	}
});